package com.hyts.gateway.base.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@SuppressWarnings("unused")
@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    /**
     * spring容器上下文操作服务
     */
    private static ApplicationContext applicationContext;

    /**
     * 获取applicationContext
     *
     * @return applicationContext
     */
    private static ApplicationContext getApplicationContext() {
        return ApplicationContextHolder.applicationContext;
    }

    /**
     * 设置相关的applicationContext对象操作机制
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    /**
     * 通过name获取 Bean.
     *
     * @param name bean的名称
     * @return bean
     */
    public static Object getBean(String name) {
        return ApplicationContextHolder.getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz class
     * @param <T>   T
     * @return bean
     */
    public static <T> T getBean(Class<T> clazz) {
        return ApplicationContextHolder.getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name  bean的名称
     * @param clazz bean的class
     * @param <T>   T
     * @return bean
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return ApplicationContextHolder.getApplicationContext().getBean(name, clazz);
    }
}